package com.qfedu.spring.mybatis.controller;

import com.qfedu.spring.mybatis.entity.User;
import com.qfedu.spring.mybatis.service.UserService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author zhang
 * @Title: commonValidateAdd
 * @date : 2022/4/27 21:25
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService userService;


    @Override
    public void init() throws ServletException {
    // 在初始化方法中给userService 赋值，通过web容器，获取String 上下文
        WebApplicationContext c = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        userService = c.getBean("userService", UserService.class);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取参数
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        //调用service.login
        User user = userService.login(name, password);
        if (Objects.nonNull(user)){
            //成功，转发到成功页面
            req.getRequestDispatcher("/success.jsp").forward(req,resp);
        }else {
            // 登录失败，重定向到登录页面
            req.setAttribute("error","用户名或密码错误");
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }

    }
}
